package com.dbsop.operation.query.transport;

import com.dbsop.domain.agg.AggOperation;
import com.dbsop.domain.transport.EsAggTcCondition;
import com.dbsop.domain.transport.res.TransportUtils;
import com.dbsop.domain.transport.EsTransportCondition;
import com.dbsop.domain.transport.agg.TransportGroup;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.util.List;

/**
 * 分组条件解析
 */
@Slf4j
public class TcAggQuerySearch {

    private EsAggTcCondition esAggCondition;


    private SearchRequest searchRequest;

    public TcAggQuerySearch(EsAggTcCondition esAggCondition) {
        this.esAggCondition = esAggCondition;
        init();
    }

    public void init(){
        searchRequest =new TcQuerySearch((EsTransportCondition) esAggCondition.getEsCondition()).getSearchRequestAgg();
        SearchSourceBuilder source = searchRequest.source();
        TransportGroup group = (TransportGroup) esAggCondition.getGroup();
        if (group !=null)source.aggregation(group.aggregationBuilder());

        List<AggOperation> aggOperations = esAggCondition.getAggOperations();
        if (aggOperations!=null && aggOperations.size()>0){
            for (AggregationBuilder paresAggregationBuilder : TransportUtils.paresAggregationBuilders(aggOperations)) {
                source.aggregation(paresAggregationBuilder);
            }
        }
        source.size(esAggCondition.getRecordSize());
        log.info("条件=>" +source.toString());
    }

    public SearchRequest getSearchRequest() {
        return searchRequest;
    }
}
